<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;

class HandleTableNotFound
{
    public function handle($request, Closure $next)
    {
        try {
            return $next($request);
        } catch (QueryException $e) {
            // 检查是否是表不存在的错误
            if (strpos($e->getMessage(), "doesn't exist") !== false) {
                Log::error('表不存在错误: ' . $e->getMessage());
                //die("sadfa");
                // 尝试自动修复
                $monitorService = app(\App\Services\TableMonitorService::class);
                $monitorService->repairMissingTables('module_baoliao_post');
                
                // 重试请求
                return $next($request);
            }
            
            throw $e;
        }
    }
}
